import { login, logout,  } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {getInUserInfo, loginOut, updateOnline} from "@/api/admin";

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  userInfo:{},
  roleCode:"",
  menus:[]
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENU: (state, menus) => {
    state.menus = menus
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLE_CODE: (state, roleCode) => {
    state.roleCode = roleCode
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(res=>{
        commit('SET_TOKEN', getToken())
        resolve()
      }).catch(error=>{
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      //获取用户个人信息数据
      getInUserInfo().then(res=>{
        commit('SET_USER_INFO', res.data)
        commit('SET_ROLE_CODE', res.data.roleCode)
        commit('SET_NAME', res.data.name)
        commit('SET_MENU', res.data.menuList)
        commit('SET_AVATAR', res.data.avatar)
        sessionStorage.setItem("ucId",res.data.ucId)
        resolve()
      }).catch(error=>{
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      loginOut().then(res=>{
        resolve(res)
        removeToken()
        commit('SET_TOKEN', '')
        commit('SET_ROLE_CODE', "")
      }).catch(error=>{
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
